<template>
  <section>
    <el-row>
      <el-col :span="20">
        <el-form :inline="true" size="mini" ref="form">
          <el-form-item label="选择公司：" >
            <el-select v-model="selCompany" placeholder="请选择">
              <el-option v-for="company in companies" :key="company.id" :label="company.companyName" :value="company.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择部门：">
            <!--医院列表-选择-->
            <el-select v-model="selDepartment" placeholder="请选择">
              <el-option v-for="department in departments" :key="department.id" :label="department.name" :value="department.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row v-if="selDepartment">
      <el-button @click="addOrder" :disabled="(selCompany && selDepartment)?false:true" size="mini" type="primary">新建订单</el-button>
    </el-row>
    <el-table :data="orderList" v-if="selDepartment">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column label="订单标题" prop="title">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.title"></el-input>
          <div v-if="!scope.row.edit">{{scope.row.title}}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="state">
        <template slot-scope="scope">
          <span v-if="scope.row.state === 0" style="color: red">未支付</span>
          <span v-else-if="scope.row.state === 1">已支付√</span>
          <span v-else>{{scope.row.state}}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单类型" prop="orderType">
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.orderType"></el-input>
          <div v-if="!scope.row.edit">{{scope.row.orderType}}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单内容" width="155">
        <template slot-scope="scope">
          <el-button  @click='orderDetail(scope)' size="mini" type="text">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="155">
        <template slot-scope="scope">
          <el-button :type="scope.row.edit?'success':'primary'" @click='confirm(scope)' size="mini" icon="edit">{{scope.row.edit?'完成':'编辑'}}</el-button>
          <el-button @click='del(scope)' size="mini" :type="scope.row.edit?'text':'danger'">{{scope.row.edit?'取消':'删除'}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="订单内容" :visible.sync="showNewOrder">
      <new-order :currOrder="currOrder" :department="selDepartment"></new-order>
    </el-dialog>
    <el-dialog title="订单内容" :visible.sync="showCurrOrder">
      <el-row style="font-weight: bold">
        <el-col :span="2.5">订单标题：</el-col>
        <el-col :span="8">
          <span v-if="currOrder.id" :span="15" >{{currOrder.title}}
              <i class="el-icon-close" slot="suffix" @click="handleIconTitle(inputTitle)"></i></span>
          <span  v-else :span="15">
            <el-input v-model="currOrder.title" @keydown.native.prevent.enter="confirmOrderTitle(inputTitle)" placeholder="请输入订单标题" size="mini">
            </el-input>
          </span>
        </el-col>
        <el-col :span="2.5" style="margin-left: 20px">订单类型：</el-col>
        <el-col :span="8">
          <span v-if="currOrder.id" :span="15" >{{currOrder.orderType}}
              <i class="el-icon-close" slot="suffix" @click="handleIconType(inputType)"></i></span>
          <span  v-else :span="15">
            <el-input popper-class="my-autocomplete" v-model="currOrder.orderType" @keydown.native.prevent.enter="confirmOrderType(inputType)" placeholder="请输入订单类型" size="mini">
            </el-input>
          </span>
        </el-col>
        <el-col :span="5" style="margin-left: 30px">
        </el-col>
      </el-row>
      <el-row v-if="currOrder.id" style="font-weight: bold;margin-top: 10px">
        订单状态：
        <span v-if="currOrder.state === 0" style="color: red">未支付</span>
        <span v-else-if="currOrder.state === 1">已支付√</span>
        <span v-else>{{currOrder.state}}啥</span>
      </el-row>
      <el-row style="font-weight: bold; margin: 15px 0 10px 0">
        <el-col :span="2">请选择:</el-col>
        <el-col :span="8" style="margin-left: 14px">
          <el-select v-model="selGoods" placeholder="商品" size="mini">
            <el-option v-for="goods in goodsList" :key="goods.id" :label="goods.name" :value="goods.id"></el-option>
          </el-select>
        </el-col>
        <el-col  :span="10">
          <el-select v-model="selGoodsSku" placeholder="商品规格" size="mini"  @visible-change="test">
            <el-option v-for="goodsSku in goodsSkus" :key="goodsSku.id" :label="goodsSku.props" :value="goodsSku.id"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <!--'orderId','title','price','num','sn'-->
        <el-table :data="currOrder.orderItems">
          <el-table-column type="index"></el-table-column>
          <el-table-column label="规格" prop="title"  width="130">
          </el-table-column>
          <el-table-column label="单价" prop="price">
          </el-table-column>
          <el-table-column label="编码" prop="sn" width="150">
          </el-table-column>
          <el-table-column label="数量" width="155">
            <template slot-scope="scope">
              <div class="numBox">
                <div  @click='increase(scope.row)' >
                  <i  class="el-icon-plus" size="mini" ></i>
                </div>
                <div class="num">
                  {{scope.row.num}}
                </div>
                <div  @click='decrease(scope.row)' >
                  <i class="el-icon-minus" size="mini"></i>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="totalPrice">
          </el-table-column>
        </el-table>
      </el-row>
      <el-row style="font-weight: bold;margin-top: 20px">
        <el-button v-if="!currOrder.id" @click="subOrder()">提交订单</el-button>
        <el-button v-if="currOrder.id" @click="payOrder(currOrder)">支付结算</el-button>
        <el-button v-if="currOrder.id" @click='del(currOrder.id)' size="mini" >删除订单</el-button>
      </el-row>
    </el-dialog>
  </section>
</template>

<script>
  import newOrder from './newOrder'
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import DateFormat from '@/common/date-formater'
  import schedule from "../../sdk/api/schedule"
  import department from "../../sdk/api/department"
  import Vue from 'vue'//后续添加属性，需要vue联动
  import errHandler from '@/assets/errHandler'
  export default {
    name: "order",
    components:{newOrder},
    data() {
      return {
        companies:[],
        selCompany:null,
        selDepartment:null,
        departments:[],
        orderList:[],
        showCurrOrder:false,
        showNewOrder:false,
        currOrder:{title:null,orderType:null,orderItems:[]},
        inputTitle:null,
        inputType:null,
        goodsList:null,
        selGoods:null,
        goodsSkus:null,
        selGoodsSku:null
      }
    },
    created(){
      //加载公司列表
      this.loadCompanies()
      console.log(this.currOrder.title)
    },
    computed:{
    },
    watch:{
      inputTitle(nv,ov){
        console.log(nv)
      },
      inputType(nv,ov){

      },
      selCompany(nv,ov){
        //根据选择的公司加载部门
        console.log(nv)
        console.log(ov)
        if(nv){
          this.loadDepartments(nv)
          this.orderList=null
        }
      },
      selDepartment(nv,ov){
        //获取商品列表
        // this.getGoodsList(nv)
        //获取订单列表
        this.getOrderList(nv)
      },
      selGoods(nv,ov){
        //获取规格列表
        this.getGoodsSkuList(nv)
      },
      selGoodsSku(nv,ov){
        console.log(nv)
        if(nv){
          let sku = this.goodsSkus.find(s => s.id === nv)//找到选中的这个商品sku
          sku.title = sku.props
          let orderItems = this.currOrder.orderItems
          console.log(sku)
          if(orderItems && orderItems.length >0){//如果当前订单规格存在并且有内容，就找一找选中的规格在订单规格内有没有
            let index = orderItems.findIndex(i => i.sn === sku.sn)
            console.log(index)
            if(index >= 0){//存在这个sku，那就数量+1
              this.increase(orderItems[index])
            }else {//不存在，就增加这个sku
              let tmp = {...sku,edit:false,num:1}
              tmp.totalPrice = tmp.num*sku.price
              orderItems.push(tmp)
            }
          }else {//如果当前订单规格不存在或者没有内容，就直接增加sku
            //不存在，就增加这个sku
            let tmp = {...sku,edit:false,num:1}
            tmp.totalPrice = tmp.num*sku.price
            orderItems.push(tmp)
          }
        }
      }
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      confirmOrderTitle(e){
        console.log(e)
        if(e){
          this.currOrder.title=e
        }
        console.log(this.currOrder.title)
      },
      confirmOrderType(e){
        console.log(e)
        if(e){
          this.currOrder.orderType=e
        }
      },
      handleIconTitle(e){
        console.log(this.currOrder.title)
        if(e){
          this.inputTitle = null
          if(this.currOrder.title){
            this.inputTitle = null
            this.currOrder.title = null
          }
        }
        console.log(this.currOrder.title)
      },
      handleIconType(e){
        console.log(this.currOrder.orderType)
        if(e){
          this.inputType = null
          if(this.currOrder.orderType){
            this.inputType = null
            this.currOrder.orderType = null
          }
        }
      },
      addOrder(){
        this.showNewOrder=true
        this.currOrder={title:'新订单',orderType:null,orderItems:[]}
        return
        console.log(this.currOrder)
        this.inputTitle = null
        this.inputType = null
        this.currOrder={title:null,orderType:null,orderItems:[]}
        this.showCurrOrder = true
        console.log(this.currOrder)
      },
      test(e){
        console.log(e)
        if(e === true){
          this.selGoodsSku = null
        }
      },
      increase(row){//增加数量
        console.log(row)
        row.num +=1
        row.totalPrice +=row.price
      },
      decrease(row){//减少数量
        row.num -=1
        row.totalPrice -=row.price
        if(row.num === 0){
          console.log(row)
          console.log(this.currOrder)
          let index = this.currOrder.orderItems.findIndex(o => o.id === row.id )
          if(index >=0){
            this.currOrder.orderItems.splice(index,1)
          }
        }
      },
      getGoodsList(departmentId){
        this.fetch({name:"getGoodsList",data:{departmentId}})
          .then(res=>{
            console.log(res)
            this.goodsList = res.content
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getGoodsSkuList(goodsId){
        this.fetch({name:"getGoodsSkuList",data:{goodsId}})
          .then(res=>{
            console.log(res)
            this.goodsSkus = res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      payOrder(o){
        console.log(o)
      },
      subOrder(){
        console.log(this.currOrder)
        //'orderId','title','price','num','sn'
        let orderItems=[]
        for(let i=0;i<this.currOrder.orderItems.length;i++){
          let tmp = this.currOrder.orderItems[i]
          let o = {
            // orderId:this.currOrder.id,
            title:tmp.props,
            price:tmp.price,
            totalPrice:tmp.totalPrice,
            num:tmp.num,
            sn:tmp.sn
          }
          orderItems.push(o)
        }
        console.log('订单项————————————————————',orderItems)//'title','orderType'   departmentId/departmentCode、orderType、data(选)、orderItems(选)
        let data = {
          title:this.currOrder.title,
          orderType:this.currOrder.orderType,
          departmentId:this.selDepartment,
          orderItems:JSON.stringify(orderItems),
          data:{
            customerId:customerId?customerId:null
          }
        }
        console.log(data)
        this.fetch({name:"createOrder",data:data})
          .then(res=>{
            console.log(res)
            this.showCurrOrder =false
            this.$message('提交成功')
            //进入结算
            this.payOrder(res)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      loadCompanies(){//加载公司列表
        this.fetch({name:"getCompanyList"})
          .then(res=>{
            this.companies = res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      loadDepartments(companyId){//加载部门列表
        this.fetch({name:"getDepartmentList",data:{companyId}})
          .then(res=>{
            this.departments=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      del(scope){
        console.log(scope)
        if(scope.row){
          if(scope.row.edit){//如果是true，就是取消
            if(scope.row.id){
              scope.row.edit = false
            }
          }else {//如果是false，就是删除
            if(scope.row.id){
              this.delOrder(scope.row.id)
            }else {
              console.log('没有id号')
            }
          }
        }else {
          this.delOrder(scope)
        }
      },
      delOrder(id){
        this.fetch({name:"delOrder",data:{id}})
          .then(res=>{
            console.log(res)
            let index = this.orderList.findIndex(o => o.id ===id)
            if(index>=0){
              this.orderList.splice(index,1)
            }
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      confirm(scope){
        console.log(scope)
        if(scope.row.edit && scope.row.edit === true){//目前是编辑状态
          let data={title:scope.row.title,orderType:scope.row.orderType,departmentId:this.selDepartment}
          //判断是否新创建
          if(scope.row.id){//更新
            data.id = scope.row.id
            this.updateOrder(data)
          }
          else {//新建
            this.createOrder(data)
          }
        }else {
          if(scope.row.edit === undefined){
            Vue.set(scope.row,'edit',true)//后续添加属性，需要vue联动
          }else {
            scope.row.edit = true
          }
        }
      },
      createOrder(data){//创建订单，'title','orderType',departmentId/departmentCode、data(选)、orderItems(选)
        //组装所需参数
        this.fetch({name:"createOrder",data:data})
          .then(res=>{
            console.log(res)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      updateOrder(){},
      getOrderList(departmentId){
        console.log(departmentId)
        this.fetch({name:"getOrderList",data:{page:0,departmentId}})
          .then(res=>{
            console.log(res)
            this.orderList = res.content
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      orderDetail(scope){
        this.currOrder = this.orderList[scope.$index]//定位当前商品
        console.log(this.currOrder)
        this.showCurrOrder = true
      },
      confirmOrderItem(scope){
        console.log(scope)
        if(scope.row.edit && scope.row.edit === true){//目前是编辑状态
          // let data={title:scope.row.title,orderType:scope.row.orderType,departmentId:this.selDepartment}
          //判断是否新创建
          if(scope.row.id){//更新
            data.id = scope.row.id
            this.updateOrderItem(data)
          }
          else {//新建
            this.createOrderItem(data)
          }
        }else {
          if(scope.row.edit === undefined){
            Vue.set(scope.row,'edit',true)//后续添加属性，需要vue联动
          }else {
            scope.row.edit = true
          }
        }
      },
      createOrderItem(data){//创建订单，'title','orderType',departmentId/departmentCode、data(选)、orderItems(选)
        //组装所需参数
        this.fetch({name:"createOrderItem",data:data})
          .then(res=>{
            console.log(res)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      updateOrderItem(){},
    }
  }
</script>

<style scoped>
  .numBox{
    /*border: 1px solid crimson;*/
    display: flex;
    justify-content: left;
    align-items: center;
  }
  .num{
    border: 1px solid darkgrey;
    width: 40px;
    margin:0 10px 0 10px;
    text-align: center;
    justify-content: center;
  }
</style>
